home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / hplip / fax / soapfax.pyc (.txt) < prev   
Python Compiled Bytecode  |  2009-10-28  |  18KB  |  455 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from __future__ import division
  5. import sys
  6. import os
  7. import time
  8. import cStringIO
  9. import urllib
  10. import re
  11. from base.g import *
  12. from base.codes import *
  13. from base import device, utils, codes, dime
  14. from fax import *
  15. http_result_pat = re.compile('HTTP/\\d.\\d\\s(\\d+)', re.I)
  16. TIME_FORMAT_AM_PM = 1
  17. TIME_FORMAT_24HR = 2
  18. DATE_FORMAT_MM_DD_YYYY = 1
  19. DATE_FORMAT_DD_MM_YYYY = 2
  20. DATE_FORMAT_YYYY_MM_DD = 3
  21. AM = 1
  22. PM = 0
  23. HTTP_OK = 200
  24. HTTP_ERROR = 500
  25. PIXELS_PER_LINE = 2528
  26.  
  27. class SOAPFaxDevice(FaxDevice):
  28.     
  29.     def __init__(self, device_uri = None, printer_name = None, callback = None, fax_type = FAX_TYPE_NONE, disable_dbus = False):
  30.         FaxDevice.__init__(self, device_uri, printer_name, callback, fax_type, disable_dbus)
  31.         self.send_fax_thread = None
  32.         self.upload_log_thread = None
  33.         if self.bus == 'net':
  34.             self.http_host = self.host
  35.         else:
  36.             self.http_host = 'localhost'
  37.  
  38.     
  39.     def post(self, url, post):
  40.         s = []
  41.         for k, v in post.items():
  42.             s.append('%s=%s' % (k, urllib.quote(str(v))))
  43.         
  44.         s = '&'.join(s)
  45.         log.debug(s)
  46.         data = 'POST %s HTTP/1.1\nConnection: Keep-alive\nUser-agent: hplip/2.0\nHost: %s\nContent-length: %d\nCache-control: No-cache\n\n%s' % (url, self.http_host, len(s), s)
  47.         log.log_data(data)
  48.         self.writeEWS(data)
  49.         ret = cStringIO.StringIO()
  50.         while self.readEWS(4096, ret, timeout = 5):
  51.             pass
  52.         ret = ret.getvalue()
  53.         log.log_data(ret)
  54.         self.closeEWS()
  55.         match = http_result_pat.match(ret)
  56.         
  57.         try:
  58.             code = int(match.group(1))
  59.         except (ValueError, TypeError):
  60.             code = HTTP_ERROR
  61.  
  62.         return code == HTTP_OK
  63.  
  64.     
  65.     def setPhoneNum(self, num):
  66.         return self.post('/hp/device/set_config.html', {
  67.             'FaxNumber': str(num) })
  68.  
  69.     
  70.     def getPhoneNum(self):
  71.         stream = cStringIO.StringIO()
  72.         self.getEWSUrl('/hp/device/settings_fax_setup_wizard.xml', stream)
  73.         fax_setup = utils.XMLToDictParser().parseXML(stream.getvalue())
  74.         return fax_setup['faxsetupwizard-faxvoicenumber-faxnumber']
  75.  
  76.     phone_num = property(getPhoneNum, setPhoneNum)
  77.     
  78.     def setStationName(self, name):
  79.         return self.post('/hp/device/set_config.html', {
  80.             'FaxCompanyName': str(name) })
  81.  
  82.     
  83.     def getStationName(self):
  84.         stream = cStringIO.StringIO()
  85.         self.getEWSUrl('/hp/device/settings_fax_setup_wizard.xml', stream)
  86.         fax_setup = utils.XMLToDictParser().parseXML(stream.getvalue())
  87.         return fax_setup['faxsetupwizard-userinformation-faxcompanyname']
  88.  
  89.     station_name = property(getStationName, setStationName)
  90.     
  91.     def setDateAndTime(self):
  92.         stream = cStringIO.StringIO()
  93.         self.getEWSUrl('/hp/device/settings_fax_setup_wizard.xml', stream)
  94.         fax_setup = utils.XMLToDictParser().parseXML(stream.getvalue())
  95.         timeformat = fax_setup['faxsetupwizard-time-timeformat']
  96.         
  97.         try:
  98.             timeformat = int(timeformat)
  99.         except (ValueError, TypeError):
  100.             timeformat = TIME_FORMAT_AM_PM
  101.  
  102.         log.debug('timeformat: %d' % timeformat)
  103.         dateformat = fax_setup['faxsetupwizard-date-dateformat']
  104.         
  105.         try:
  106.             dateformat = int(dateformat)
  107.         except (ValueError, TypeError):
  108.             dateformat = DATE_FORMAT_DD_MM_YYYY
  109.  
  110.         log.debug('dateformat: %d' % dateformat)
  111.         t = time.localtime()
  112.         hr = t[3]
  113.         am_pm = PM
  114.         if t[3] < 12:
  115.             am_pm = AM
  116.         
  117.         if timeformat == TIME_FORMAT_AM_PM and hr > 12:
  118.             hr -= 12
  119.         
  120.         post = {
  121.             'DateFormat': dateformat,
  122.             'Year': t[0],
  123.             'Month': t[1],
  124.             'Day': t[2],
  125.             'TimeFormat': timeformat,
  126.             'Hour': hr,
  127.             'Minute': t[4] }
  128.         if timeformat == TIME_FORMAT_AM_PM:
  129.             post['AM'] = am_pm
  130.         
  131.         return self.post('/hp/device/set_config.html', post)
  132.  
  133.     
  134.     def sendFaxes(self, phone_num_list, fax_file_list, cover_message = '', cover_re = '', cover_func = None, preserve_formatting = False, printer_name = '', update_queue = None, event_queue = None):
  135.         if not self.isSendFaxActive():
  136.             self.send_fax_thread = SOAPFaxSendThread(self, self.service, phone_num_list, fax_file_list, cover_message, cover_re, cover_func, preserve_formatting, printer_name, update_queue, event_queue)
  137.             self.send_fax_thread.start()
  138.             return True
  139.         return False
  140.  
  141.  
  142.  
  143. class SOAPFaxSendThread(FaxSendThread):
  144.     
  145.     def __init__(self, dev, service, phone_num_list, fax_file_list, cover_message = '', cover_re = '', cover_func = None, preserve_formatting = False, printer_name = '', update_queue = None, event_queue = None):
  146.         FaxSendThread.__init__(self, dev, service, phone_num_list, fax_file_list, cover_message, cover_re, cover_func, preserve_formatting, printer_name, update_queue, event_queue)
  147.         self.job_id = utils.gen_random_uuid()
  148.         log.debug('JobId: %s' % self.job_id)
  149.         if dev.bus == 'net':
  150.             self.http_host = '%s:8295' % self.dev.host
  151.         else:
  152.             self.http_host = 'localhost:8295'
  153.  
  154.     
  155.     def run(self):
  156.         STATE_DONE = 0
  157.         STATE_ABORTED = 10
  158.         STATE_SUCCESS = 20
  159.         STATE_BUSY = 25
  160.         STATE_READ_SENDER_INFO = 30
  161.         STATE_PRERENDER = 40
  162.         STATE_COUNT_PAGES = 50
  163.         STATE_NEXT_RECIPIENT = 60
  164.         STATE_COVER_PAGE = 70
  165.         STATE_SINGLE_FILE = 80
  166.         STATE_MERGE_FILES = 90
  167.         STATE_SINGLE_FILE = 100
  168.         STATE_SEND_FAX = 110
  169.         STATE_CLEANUP = 120
  170.         STATE_ERROR = 130
  171.         next_recipient = self.next_recipient_gen()
  172.         state = STATE_READ_SENDER_INFO
  173.         self.rendered_file_list = []
  174.         while state != STATE_DONE:
  175.             if self.check_for_cancel():
  176.                 state = STATE_ABORTED
  177.             
  178.             log.debug('STATE=(%d, 0, 0)' % state)
  179.             if state == STATE_ABORTED:
  180.                 log.error('Aborted by user.')
  181.                 self.write_queue((STATUS_IDLE, 0, ''))
  182.                 state = STATE_CLEANUP
  183.                 continue
  184.             if state == STATE_SUCCESS:
  185.                 log.debug('Success.')
  186.                 self.write_queue((STATUS_COMPLETED, 0, ''))
  187.                 state = STATE_CLEANUP
  188.                 continue
  189.             if state == STATE_ERROR:
  190.                 log.error('Error, aborting.')
  191.                 self.write_queue((STATUS_ERROR, 0, ''))
  192.                 state = STATE_CLEANUP
  193.                 continue
  194.             if state == STATE_BUSY:
  195.                 log.error('Device busy, aborting.')
  196.                 self.write_queue((STATUS_BUSY, 0, ''))
  197.                 state = STATE_CLEANUP
  198.                 continue
  199.             if state == STATE_READ_SENDER_INFO:
  200.                 log.debug('%s State: Get sender info' % '********************')
  201.                 state = STATE_PRERENDER
  202.                 
  203.                 try:
  204.                     self.dev.open()
  205.                 except Error:
  206.                     e = None
  207.                     log.error('Unable to open device (%s).' % e.msg)
  208.                     state = STATE_ERROR
  209.                 else:
  210.                     
  211.                     try:
  212.                         self.sender_name = self.dev.station_name
  213.                         log.debug('Sender name=%s' % self.sender_name)
  214.                         self.sender_fax = self.dev.phone_num
  215.                         log.debug('Sender fax=%s' % self.sender_fax)
  216.                     except Error:
  217.                         log.error('HTTP GET failed!')
  218.                         state = STATE_ERROR
  219.  
  220.                 finally:
  221.                     self.dev.close()
  222.  
  223.                 continue
  224.             if state == STATE_PRERENDER:
  225.                 log.debug('%s State: Pre-render non-G4 files' % '********************')
  226.                 state = self.pre_render(STATE_COUNT_PAGES)
  227.                 continue
  228.             if state == STATE_COUNT_PAGES:
  229.                 log.debug('%s State: Get total page count' % '********************')
  230.                 state = self.count_pages(STATE_NEXT_RECIPIENT)
  231.                 continue
  232.             if state == STATE_NEXT_RECIPIENT:
  233.                 log.debug('%s State: Next recipient' % '********************')
  234.                 state = STATE_COVER_PAGE
  235.                 
  236.                 try:
  237.                     recipient = next_recipient.next()
  238.                     log.debug('Processing for recipient %s' % recipient['name'])
  239.                     self.write_queue((STATUS_SENDING_TO_RECIPIENT, 0, recipient['name']))
  240.                 except StopIteration:
  241.                     state = STATE_SUCCESS
  242.                     log.debug('Last recipient.')
  243.                     continue
  244.  
  245.                 recipient_file_list = self.rendered_file_list[:]
  246.                 continue
  247.             if state == STATE_COVER_PAGE:
  248.                 log.debug('%s State: Render cover page' % '********************')
  249.                 state = self.cover_page(recipient)
  250.                 continue
  251.             if state == STATE_SINGLE_FILE:
  252.                 log.debug('%s State: Handle single file' % '********************')
  253.                 state = self.single_file(STATE_SEND_FAX)
  254.                 continue
  255.             if state == STATE_MERGE_FILES:
  256.                 log.debug('%s State: Merge multiple files' % '********************')
  257.                 state = self.merge_files(STATE_SEND_FAX)
  258.                 continue
  259.             if state == STATE_SEND_FAX:
  260.                 log.debug('%s State: Send fax' % '********************')
  261.                 state = STATE_NEXT_RECIPIENT
  262.                 FAX_SEND_STATE_DONE = 0
  263.                 FAX_SEND_STATE_ABORT = 10
  264.                 FAX_SEND_STATE_ERROR = 20
  265.                 FAX_SEND_STATE_BUSY = 25
  266.                 FAX_SEND_STATE_SUCCESS = 30
  267.                 FAX_SEND_STATE_DEVICE_OPEN = 40
  268.                 FAX_SEND_STATE_BEGINJOB = 50
  269.                 FAX_SEND_STATE_DOWNLOADPAGES = 60
  270.                 FAX_SEND_STATE_ENDJOB = 70
  271.                 FAX_SEND_STATE_CANCELJOB = 80
  272.                 FAX_SEND_STATE_CLOSE_SESSION = 170
  273.                 monitor_state = False
  274.                 fax_send_state = FAX_SEND_STATE_DEVICE_OPEN
  275.                 while fax_send_state != FAX_SEND_STATE_DONE:
  276.                     if self.check_for_cancel():
  277.                         log.error('Fax send aborted.')
  278.                         fax_send_state = FAX_SEND_STATE_ABORT
  279.                     
  280.                     if monitor_state:
  281.                         fax_state = self.getFaxDownloadState()
  282.                         if fax_state not in (pml.UPDN_STATE_XFERACTIVE, pml.UPDN_STATE_XFERDONE):
  283.                             log.error('D/L error state=%d' % fax_state)
  284.                             fax_send_state = FAX_SEND_STATE_ERROR
  285.                             state = STATE_ERROR
  286.                         
  287.                     
  288.                     log.debug('STATE=(%d, %d, 0)' % (STATE_SEND_FAX, fax_send_state))
  289.                     if fax_send_state == FAX_SEND_STATE_ABORT:
  290.                         monitor_state = False
  291.                         fax_send_state = FAX_SEND_STATE_CANCELJOB
  292.                         state = STATE_ABORTED
  293.                         continue
  294.                     if fax_send_state == FAX_SEND_STATE_ERROR:
  295.                         log.error('Fax send error.')
  296.                         monitor_state = False
  297.                         fax_send_state = FAX_SEND_STATE_CLOSE_SESSION
  298.                         state = STATE_ERROR
  299.                         continue
  300.                     if fax_send_state == FAX_SEND_STATE_BUSY:
  301.                         log.error('Fax device busy.')
  302.                         monitor_state = False
  303.                         fax_send_state = FAX_SEND_STATE_CLOSE_SESSION
  304.                         state = STATE_BUSY
  305.                         continue
  306.                     None if fax_send_state == FAX_SEND_STATE_SUCCESS else self.dev.device_state == DEVICE_STATE_NOT_FOUND
  307.                     if fax_send_state == FAX_SEND_STATE_BEGINJOB:
  308.                         log.debug('%s State: BeginJob' % '********************')
  309.                         
  310.                         try:
  311.                             ff = file(self.f, 'r')
  312.                         except IOError:
  313.                             log.error('Unable to read fax file.')
  314.                             fax_send_state = FAX_SEND_STATE_ERROR
  315.                             continue
  316.  
  317.                         
  318.                         try:
  319.                             header = ff.read(FILE_HEADER_SIZE)
  320.                         except IOError:
  321.                             log.error('Unable to read fax file.')
  322.                             fax_send_state = FAX_SEND_STATE_ERROR
  323.                             continue
  324.  
  325.                         (magic, version, total_pages, hort_dpi, vert_dpi, page_size, resolution, encoding, reserved1, reserved2) = self.decode_fax_header(header)
  326.                         if magic != 'hplip_g3':
  327.                             log.error('Invalid file header. Bad magic.')
  328.                             fax_send_state = FAX_SEND_STATE_ERROR
  329.                         else:
  330.                             log.debug('Magic=%s Ver=%d Pages=%d hDPI=%d vDPI=%d Size=%d Res=%d Enc=%d' % (magic, version, total_pages, hort_dpi, vert_dpi, page_size, resolution, encoding))
  331.                         job_id = self.job_id
  332.                         delay = 0
  333.                         faxnum = recipient['fax'].encode('ascii')
  334.                         speeddial = 0
  335.                         if resolution == RESOLUTION_STD:
  336.                             res = 'STANDARD'
  337.                         elif resolution == RESOLUTION_FINE:
  338.                             res = 'FINE'
  339.                         elif resolution == RESOLUTION_300DPI:
  340.                             res = 'SUPERFINE'
  341.                         
  342.                         soap = utils.cat('<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><Fax:BeginJob xmlns:Fax="urn:Fax"><ticket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Fax:Ticket"><jobId xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="xsd:string">$job_id</jobId><resolution xsi:type="Fax:Resolution">$res</resolution><delay xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="xsd:positiveInteger">$delay</delay><phoneNumber xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="xsd:string">$faxnum</phoneNumber><speedDial xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="xsd:positiveInteger">$speeddial</speedDial></ticket></Fax:BeginJob></SOAP-ENV:Body></SOAP-ENV:Envelope>')
  343.                         data = self.format_http(soap)
  344.                         log.log_data(data)
  345.                         if log.is_debug():
  346.                             file('beginjob.log', 'w').write(data)
  347.                         
  348.                         self.dev.openSoapFax()
  349.                         self.dev.writeSoapFax(data)
  350.                         ret = cStringIO.StringIO()
  351.                         while self.dev.readSoapFax(8192, ret, timeout = 5):
  352.                             pass
  353.                         ret = ret.getvalue()
  354.                         if log.is_debug():
  355.                             file('beginjob_ret.log', 'w').write(ret)
  356.                         
  357.                         log.log_data(ret)
  358.                         self.dev.closeSoapFax()
  359.                         if self.get_error_code(ret) == HTTP_OK:
  360.                             fax_send_state = FAX_SEND_STATE_DOWNLOADPAGES
  361.                         else:
  362.                             fax_send_state = FAX_SEND_STATE_ERROR
  363.                     self.get_error_code(ret) == HTTP_OK
  364.                     None if fax_send_state == FAX_SEND_STATE_DOWNLOADPAGES else self.get_error_code(ret) == HTTP_OK
  365.                     if fax_send_state == FAX_SEND_STATE_CANCELJOB:
  366.                         log.debug('%s State: CancelJob' % '********************')
  367.                         job_id = self.job_id
  368.                         soap = utils.cat('<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header><jobId xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string" SOAP-ENV:mustUnderstand="1">$job_id</jobId></SOAP-ENV:Header><SOAP-ENV:Body><Fax:CancelJob xmlns:Fax="urn:Fax"><jobId xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">$job_id</jobId></Fax:CancelJob></SOAP-ENV:Body></SOAP-ENV:Envelope>')
  369.                         data = self.format_http(soap)
  370.                         log.log_data(data)
  371.                         if log.is_debug():
  372.                             file('canceljob.log', 'w').write(data)
  373.                         
  374.                         self.dev.writeSoapFax(data)
  375.                         ret = cStringIO.StringIO()
  376.                         while self.dev.readSoapFax(8192, ret, timeout = 5):
  377.                             pass
  378.                         ret = ret.getvalue()
  379.                         if log.is_debug():
  380.                             file('canceljob_ret.log', 'w').write(ret)
  381.                         
  382.                         log.log_data(ret)
  383.                         self.dev.closeSoapFax()
  384.                         if self.get_error_code(ret) == HTTP_OK:
  385.                             fax_send_state = FAX_SEND_STATE_CLOSE_SESSION
  386.                         else:
  387.                             fax_send_state = FAX_SEND_STATE_ERROR
  388.                     self.get_error_code(ret) == HTTP_OK
  389.                     if fax_send_state == FAX_SEND_STATE_CLOSE_SESSION:
  390.                         log.debug('%s State: Close session' % '********************')
  391.                         log.debug('Closing session...')
  392.                         
  393.                         try:
  394.                             mm.close()
  395.                         except NameError:
  396.                             pass
  397.  
  398.                         
  399.                         try:
  400.                             ff.close()
  401.                         except NameError:
  402.                             pass
  403.  
  404.                         time.sleep(1)
  405.                         self.dev.closeSoapFax()
  406.                         self.dev.close()
  407.                         fax_send_state = FAX_SEND_STATE_DONE
  408.                         continue
  409.                 continue
  410.             if state == STATE_CLEANUP:
  411.                 log.debug('%s State: Cleanup' % '********************')
  412.                 if self.remove_temp_file:
  413.                     log.debug('Removing merged file: %s' % self.f)
  414.                     
  415.                     try:
  416.                         os.remove(self.f)
  417.                         log.debug('Removed')
  418.                     except OSError:
  419.                         log.debug('Not found')
  420.                     except:
  421.                         None<EXCEPTION MATCH>OSError
  422.                     
  423.  
  424.                 None<EXCEPTION MATCH>OSError
  425.                 state = STATE_DONE
  426.                 continue
  427.  
  428.     
  429.     def get_error_code(self, ret):
  430.         if not ret:
  431.             return HTTP_ERROR
  432.         match = http_result_pat.match(ret)
  433.         if match is None:
  434.             return HTTP_OK
  435.         
  436.         try:
  437.             code = int(match.group(1))
  438.         except (ValueError, TypeError):
  439.             match is None
  440.             match is None
  441.             ret
  442.             code = HTTP_ERROR
  443.         except:
  444.             match is None
  445.  
  446.         return code
  447.  
  448.     
  449.     def format_http(self, soap, content_type = 'text/xml; charset=utf-8'):
  450.         host = self.http_host
  451.         soap_len = len(soap)
  452.         return utils.cat('POST / HTTP/1.1\r\nHost: $host\r\nUser-Agent: hplip/2.0\r\nContent-Type: $content_type\r\nContent-Length: $soap_len\r\nConnection: close\r\nSOAPAction: ""\r\n\r\n$soap')
  453.  
  454.  
  455.